#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

#define START		0
#define END			3
#define THR_COUNT	5

static int next = 0;

static void *thr_job(void *s);

static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;

static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

int main(void)
{
	pthread_t tids[THR_COUNT];
	int args[][THR_COUNT] = {{0}, {1}, {2}, {3}, {4}};
	int err, i, j;

	for (i = 0; i < THR_COUNT; i++) {
		err = pthread_create(&tids[i], NULL, thr_job, (void *) args[i]);
		//printf("Started thread [%d]\n", *args[i]);

		if (err) {
			fprintf(stderr, "Error creating thread: %s\n", strerror(err));
			exit(1);
		}
	}

	for (i = 0; i < THR_COUNT; i++) { // 分别给每个线程収尸（实际结束不了）
		pthread_join(tids[i], NULL);
	}

	pthread_mutex_destroy(&mut);

	return 0;
}

static void *thr_job(void *s)
{
	int t = *((int *) s); // 这是哪一个线程
	
	while (1) {
		pthread_mutex_lock(&mut);
		
		while (next != t) { // 没轮到呢，等
			//printf("Thread [%d] wait. next: [%d]\n", t, next);
			pthread_cond_wait(&cond, &mut);
		}

		//printf("Thread [%d]: %c next: [%d]\n", t, 'a' + t, next);
		fputc('a' + t, stdout);
		fflush(stdout);
		
		next = (next + 1) % THR_COUNT;
		
		pthread_cond_broadcast(&cond);
		pthread_mutex_unlock(&mut);

		sleep(1);
	}

	return (void *) 0;
}

